import router from '@/router';
import { defineStore } from 'pinia'
import { Ref, ref } from "vue";
import Cache from "@/common/utils/cache";
export const useStore = defineStore('tags', () => {
  const tags: Ref<any[]> = ref([]);
  const tag: Ref<any> = ref('');

  // 添加标签
  const addTag = (e: any) => {
    const parentView = e.matched.find(x => x.meta?.type === "1");
    const view = {
      name: e.name,
      meta: e.meta,
      parentView: {
        name: parentView.name,
        path: parentView.path,
        meta: parentView.meta,
        children: parentView.children,
      },
      query: e.query,
      params: e.params,
    };
    const oldViewIdx = tags.value.findIndex(x => x.parentView.name === view.parentView.name);
    // 存在已激活tag时
    if (oldViewIdx > -1) {
      tags.value.splice(oldViewIdx, 1, view);
    } else {
      tags.value.push(view);
    }
    addCachedView(e);
  }

  // 简单移除标签,不执行跳转动作
  const removeTagSimple = (e: any) => {
    tags.value.splice(tags.value.findIndex(x => x.name === e.name), 1);
    delCachedView(e);
  }

  // 移除标签
  const removeTag = async (e: any, next?: string) => {
    removeTagSimple(e);
    if (next) {
      tag.value = next;
    } else {
      tag.value = tags?.value?.[tags.value.length - 1]?.name;
    }
    if (tag.value) {
      router.push({
        name: tags.value.find(x => x.name === tag.value).name,
        query: tags.value.find(x => x.name === tag.value).query,
        params: tags.value.find(x => x.name === tag.value).params,
      });
    } else {
      router.push("/");
    }
  }

  // 标签切换
  const tagChange = (e: any) => {
    tag.value = e?.name;
  }

  const cachedViews: Ref<any[]> = ref([]);
  const addCachedView = (view) => {
    if (cachedViews.value.includes(view?.name)) return;
    if (view?.meta && !view?.meta?.noCache) {
      cachedViews.value.push(view?.name);
    }
  }
  const delCachedView = (view) => {
    //删除当前路由缓存
    const index1 = cachedViews.value.indexOf(view.name);
    index1 > -1 && cachedViews.value.splice(index1, 1);
    //当前路由父级如果type=2所有子路由缓存都清空
    const parentView = view?.parentView;
    if (parentView?.meta?.type === "1") {
      const children = view?.parentView?.children;
      children?.forEach(x => {
        const index2 = cachedViews.value.indexOf(x.name);
        index2 > -1 && cachedViews.value.splice(index2, 1);
      })
    }
  }
  // 初始化
  const init = () => {
    tags.value = [];
    cachedViews.value = [];
    tag.value = "";
  }
  return {
    cachedViews,
    addCachedView,
    delCachedView,
    tags,
    tag,
    addTag,
    removeTagSimple,
    removeTag,
    tagChange,
    init,
  }
}, {
  persist: {
    enabled: true,
    key: new Cache().defineKey('tags'),
    storage: sessionStorage,
  }
} as any)
